package com.example.huixue.controller;

import com.example.huixue.common.Result;
import com.example.huixue.entity.Rating;
import com.example.huixue.service.RatingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
public class RatingController {
    
    private static final Logger logger = LoggerFactory.getLogger(RatingController.class);
    
    @Autowired
    private RatingService ratingService;
    
    /**
     * 提交评分
     */
    @PostMapping({"/resources/{resourceId}/rating", "/api/resources/{resourceId}/rating"})
    public Result<?> rateResource(@PathVariable Long resourceId, 
                                 @RequestBody Map<String, Object> ratingData,
                                 @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            logger.info("提交评分请求: resourceId={}", resourceId);
            
            Integer rating = (Integer) ratingData.get("rating");
            String comment = (String) ratingData.get("comment");
            
            if (rating == null || rating < 1 || rating > 5) {
                return Result.error("评分必须在1-5星之间");
            }
            
            // 从token获取用户ID，如果没有token使用默认用户ID
            Long userId = 1L; // 默认用户ID，实际应该从token解析
            if (token != null && token.startsWith("Bearer ")) {
                try {
                    String actualToken = token.substring(7);
                    if (actualToken.startsWith("mock-jwt-token-")) {
                        userId = Long.parseLong(actualToken.replace("mock-jwt-token-", ""));
                    }
                } catch (Exception e) {
                    logger.warn("解析token失败: {}", e.getMessage());
                }
            }
            
            // 调用服务层提交评分
            ratingService.submitRating(userId, resourceId, rating, comment);
            
            return Result.success("评分成功");
        } catch (Exception e) {
            logger.error("提交评分失败", e);
            return Result.error("提交评分失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取资源评分统计
     */
    @GetMapping({"/resources/{resourceId}/rating/stats", "/api/resources/{resourceId}/rating/stats"})
    public Result<?> getRatingStats(@PathVariable Long resourceId) {
        try {
            logger.info("获取评分统计请求: resourceId={}", resourceId);
            
            Map<String, Object> stats = ratingService.getResourceRatingStats(resourceId);
            return Result.success("获取评分统计成功", stats);
        } catch (Exception e) {
            logger.error("获取评分统计失败", e);
            return Result.error("获取评分统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户对资源的评分
     */
    @GetMapping({"/resources/{resourceId}/rating/user/{userId}", "/api/resources/{resourceId}/rating/user/{userId}"})
    public Result<?> getUserRating(@PathVariable Long resourceId, @PathVariable Long userId) {
        try {
            logger.info("获取用户评分请求: resourceId={}, userId={}", resourceId, userId);
            
            Rating userRating = ratingService.getUserRating(userId, resourceId);
            if (userRating != null) {
                return Result.success("获取用户评分成功", Map.of(
                    "rating", userRating.getScore(),
                    "comment", userRating.getComment() != null ? userRating.getComment() : ""
                ));
            } else {
                return Result.success("获取用户评分成功", Map.of("rating", 0, "comment", ""));
            }
        } catch (Exception e) {
            logger.error("获取用户评分失败", e);
            return Result.error("获取用户评分失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取资源评论列表
     */
    @GetMapping({"/resources/{resourceId}/rating/comments", "/api/resources/{resourceId}/rating/comments"})
    public Result<?> getResourceComments(@PathVariable Long resourceId,
                                        @RequestParam(defaultValue = "1") int page,
                                        @RequestParam(defaultValue = "10") int size) {
        try {
            logger.info("获取资源评论列表请求: resourceId={}, page={}, size={}", resourceId, page, size);
            
            Map<String, Object> comments = ratingService.getResourceComments(resourceId, page, size);
            return Result.success("获取评论列表成功", comments);
        } catch (Exception e) {
            logger.error("获取评论列表失败", e);
            return Result.error("获取评论列表失败：" + e.getMessage());
        }
    }
} 